<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="操作类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择操作类型" clearable>
          <el-option v-for="dict in outAndIn" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="handleHame">
        <el-select v-model="queryParams.handleHame" placeholder="请选择负责人" clearable @change="handleQuery">
              <el-option v-for="(dict,i) in rw_user_list" :key="i" :label="dict.label" :value="dict.value" />
          </el-select>
      </el-form-item>
      <el-form-item label="处理时间" prop="handleTime">
        <el-date-picker clearable v-model="queryParams.handleTime" type="date" value-format="YYYY-MM-DD"
          placeholder="选择处理时间" />
      </el-form-item>
       
      <el-form-item>
        <el-button type="primary" icon="Search" @click=" handleQuery ">搜索</el-button>
        <el-button icon="Refresh" @click=" resetQuery ">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter=" 10 " class="mb8">
      <el-col :span=" 1.5 ">
        <el-button size="small" type="primary" plain icon="Plus" @click=" handleAdd "
          v-hasPermi=" ['manage:record:add'] ">新增</el-button>
      </el-col>
      <el-col :span=" 1.5 ">
        <el-button size="small" type="danger" plain icon="Delete" :disabled=" multiple " @click=" handleDelete "
          v-hasPermi=" ['manage:record:remove'] ">删除</el-button>
      </el-col>
      <el-col :span=" 1.5 ">
        <el-button size="small" type="warning" plain icon="Download" @click=" handleExport "
          v-hasPermi=" ['manage:record:export'] ">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch=" showSearch " @queryTable=" getList "></right-toolbar>
    </el-row>
    <el-table v-loading=" loading " :data=" recordList " @selection-change=" handleSelectionChange " border @row-click="(row)=>{console.log(row)}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" type="index" width="60" />
      <el-table-column label="名称" align="center">
        <template #default="scope">
                    <span>{{scope.row.rwProductLibrary.productName || ''}}</span>
                </template>
      </el-table-column>
	  <el-table-column label="操作类型" align="center" prop="type">
        <template #default="scope">
                    <dict-tag :options="outAndIn" :value="scope.row.type" />
                </template>
      </el-table-column>
      <el-table-column label="入库/出库数量" align="center" prop="inStorage" />
      <el-table-column label="处理人" align="center" prop="handleHame" />
      <el-table-column label="操作时间" align="center" prop="handleTime" width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link icon="Edit" class="table_link_btn" type="primary" :underline="false" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:content:edit']"><span class="table_link_text">修改</span></el-link>
            <el-link icon="Delete" class="table_link_btn" type="danger" :underline="false" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:content:edit']"><span class="table_link_text">删除</span></el-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show=" total > 0 " :total=" total " v-model:page=" queryParams.pageNum "
      v-model:limit=" queryParams.pageSize " @pagination=" getList " />

    <!-- 添加或修改出入库记录对话框 -->
    <el-dialog :title=" title " v-model=" open " width="550px" append-to-body>
      <el-form ref="recordRef" :model=" form " :rules=" rules " label-width="100px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" class="w-300">
            <el-option label="入库" value="1" />
            <el-option label="出库" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品" prop="productId">
          <el-select v-model="form.productId" placeholder="请选择商品" clearable filterable class="w-300px">
              <el-option v-for="dict in productList" :key="dict.id" :label="dict.productName"
                  :value="dict.id" />
          </el-select>
          <el-tooltip
            :content="showStr"
            raw-content placement="right">
            <span class="text-blue cursor-pointer ml-20">显示商品详情</span>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="出/入库数量" prop="inStorage">
          <el-input-number v-model="form.inStorage" controls-position="right" :min="1" :max="maxNum" class="w-300" />
          <span class="ml-20px">{{ productUnit }}</span>
        </el-form-item>
        <el-form-item label="处理时间" prop="handleTime">
          <el-date-picker v-model="form.handleTime" type="datetime" placeholder="选择处理时间" :shortcuts="shortcuts" class="w-300" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="负责人" prop="handleHame" >
          <el-select v-model="form.handleHame" placeholder="请选择负责人" clearable>
              <el-option v-for="(dict,i) in rw_user_list" :key="i" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click=" submitForm ">确 定</el-button>
          <el-button @click=" cancel ">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record" lang="ts">
import { listProduct } from '../rwproduct/api/product';
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from './api/record';
import { getCurrentInstance ,ref, watch} from 'vue';

const { proxy } = getCurrentInstance() as any;
const { rw_user_list } = proxy.useDict('rw_user_list');
const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<any[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const form = ref<any>({});
const queryParams = ref({
	pageNum: 1,
	pageSize: 10,
	productId: '', productName: null,  handleHame: '', handleTime: '', type: ''
});
const shortcuts = [
	{
		text: '今天',
		value: new Date(),
	},
	{
		text: '昨天',
		value: () => {
			const date = new Date();
			date.setDate(date.getDate() - 1);
			return date;
		},
	},
	{
		text: '一周前',
		value: () => {
			const date = new Date();
			date.setDate(date.getDate() - 7);
			return date;
		},
	},
];
const rules = ref({
	type: [
		{
			required: true,
			message: '类型不能为空',
			trigger: ['blur', 'change'],
		},
	],
	productId: [
		{
			required: true,
			message: '商品不能为空',
			trigger: ['blur', 'change'],
		},
	],
	inStorage: [
		{
			required: true,
			message: '出/入库数量不能为空',
			trigger: ['blur', 'change'],
		},
	],
	handleHame: [
		{
			required: true,
			message: '处理人不能为空',
			trigger: ['blur', 'change'],
		},
	],
	handleTime: [
		{
			required: true,
			message: '处理时间不能为空',
			trigger: ['blur', 'change',''],
		},
	],
});

const outAndIn = [
	{
		label:'入库',
		value:'1'
	},
	{
		label:'出库',
		value:'2'
	},
];
/** 查询出入库记录列表 */
function getList() {
	loading.value = true;
	listRecord(queryParams.value).then((response:any) => {
		recordList.value = response.data.list;
		total.value = response.data.total;
		loading.value = false;
	});
}
// 获取其他信息
const productList = ref<any[]>([]);
async function getOther(){
	const {data} = await listProduct({});
	productList.value = data.list;
	console.log(data,productList.value ,'产品列表');
}

// 取消按钮
function cancel() {
	open.value = false;
	reset();
}

// 表单重置
function reset() {
	form.value = {
		id: null, productId: '', productName: null, inStorage: 1, handleHame: null, handleTime: null, type: null
	};
	proxy.resetForm('recordRef');
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	getList();
}

/** 重置按钮操作 */
const queryRef = ref('');
function resetQuery() {
	proxy.resetForm(queryRef);
	handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection:any) {
	ids.value = selection.map((item:any) => item.id);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
	reset();
	open.value = true;
	title.value = '添加出入库记录';
}

/** 修改按钮操作 */
function handleUpdate(row:any) {
	reset();
	const id = row.id || ids.value;
	getRecord(id).then(response => {
		form.value = response.data;
		open.value = true;
		title.value = '修改出入库记录';
	});
}

/** 提交按钮 */
function submitForm() {
	proxy.$refs['recordRef'].validate((valid:boolean) => {
		if (valid) {
			if (form.value.id != null) {
				updateRecord(form.value).then(response => {
					proxy.$modal.msgSuccess('修改成功');
					open.value = false;
					getList();
				});
			} else {
				addRecord(form.value).then(response => {
					proxy.$modal.msgSuccess('新增成功');
					open.value = false;
					getList();
				});
			}
		}
	});
}

/** 删除按钮操作 */
function handleDelete(row:any) {
	const res = row.id || ids.value;
	proxy.$modal.confirm('是否确认删除出入库记录编号为"' + res + '"的数据项？').then(function () {
		return delRecord(res);
	}).then(() => {
		getList();
		proxy.$modal.msgSuccess('删除成功');
	}).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
	proxy.download('rwmanage/record/exportByStream', {
		...queryParams.value
	}, `record_${new Date().getTime()}.xlsx`);
}
let showStr = ref('<span>暂无数据,请选择!</span>');
let maxNum = ref(100000000000);
let productUnit = ref('kg');
watch(()=>[form.value.productId,form.value.type],(newVal)=>{
	console.log(newVal);
	const res = productList.value.find((ele: any) => ele.id === newVal[0]);
	if(res){
		showStr.value = showHtml(res);
		// 如果出库需要限制下出库的数量，不能超过
		maxNum.value = newVal[1] === '2' ? res.storageQuantity : 100000000000;
		productUnit.value = res.productUnit;
	}else{
		showStr.value = '<span>请选择商品!</span>';
		maxNum.value = 100000000000;
		productUnit.value = 'KG';
	}
});
function showHtml(str:any){
	console.log(str);
	return `
    <li>产品名称 : ${str.productName}</li>
    <li>产品宽度 : ${str.productWidth} cm</li>
    <li>产品长度 : ${str.productLength} cm</li>
    <li>产品颜色 : ${str.fabricColor}</li>
    <li>产品品牌 : ${str.brand}</li>
  `;
}

getList();
getOther();
</script>
